import {BasePage, BasePageData} from "../common/core/BasePage";
import {DataLoader, field} from "../../modules/coreModule/data/DataLoader";
import {Banner, bannerRepo} from "../../modules/miscModule/data/Banner";
import {TaskIndexData, TaskStatus, TaskType} from "../../modules/taskModule/data/Task";
import {page, pageFunc} from "../common/PageBuilder";
import {UserPage} from "../common/partPages/UserPage";
import {QueryPage} from "../common/partPages/QueryPage";
import {waitForLogin} from "../../modules/userModule/managers/UserManager";
import {waitForDataLoad} from "../../modules/coreModule/managers/DataManager";
import {TaskInterface} from "../../modules/taskModule/TaskCommon";
import {blockLoading, showLoading} from "../../modules/coreModule/managers/LoadingManager";
import {CoreLoading} from "../../modules/coreModule/CoreCommon";

enum Order {Rand = 0, Desc = -1, Asc = 1}

class Data extends BasePageData {

	@field([Banner])
	banners: Banner[] = []
	@field([TaskIndexData])
	tasks: TaskIndexData[] = [];

	@field(Order)
	salaryOrder: Order = Order.Rand;

	@field(Order)
	timeOrder: Order = Order.Rand;
}

// const FilterStatuses = [TaskStatus.Normal]

@page("camp", "成长训练营")
export class CampPage extends BasePage<Data> {

	data = new Data();

	public userPage = new UserPage();
	public queryPage: QueryPage = new QueryPage(
		this.loadTasks.bind(this), {
			type: TaskType.Military, // 互换
			status: TaskStatus.Normal
		});

	async onLoad(e) {
		super.onLoad(e);
		await this.loadData();
	}

	@showLoading(CoreLoading.Mask)
	@blockLoading
	@waitForLogin
	@waitForDataLoad
	private async loadData() {
		this.queryPage.refresh();
		await this.setData({
			banners: bannerRepo().find(),
			// tasks: await this.loadTasks({offset: 0, count: 20})
		})
	}

	/**
	 * 根据当前排序状态提供offset和count获得task
	 * @param queryParams
	 */
	@pageFunc
	@showLoading(CoreLoading.Mask)
	@blockLoading
	private async loadTasks(queryParams) {
		const extraParams = {
			sortSalary: this.data.salaryOrder,
			sortTime: this.data.timeOrder
		};
		let newTasks = (await TaskInterface.GetTasks(
			{...queryParams, ...extraParams}
		)).tasks.map(t =>
			DataLoader.load(TaskIndexData, t)
		)
		await this.setData({
			tasks: this.data.tasks.concat(newTasks)
		})
	}

	@pageFunc
	public async sortByPrice() {
		await this.setData({
			salaryOrder: this.data.salaryOrder ?
				-this.data.salaryOrder : Order.Asc,
			timeOrder: Order.Rand,
			tasks: []
		})
		this.queryPage.refresh();
	}

	@pageFunc
	public async sortByTime() {
		await this.setData({
			timeOrder: this.data.timeOrder ?
				-this.data.timeOrder : Order.Asc,
			salaryOrder: Order.Rand,
			tasks: []
		})
		this.queryPage.refresh();
	}

	// @pageFunc
	// public hintForFee() {
	// 	alertMgr().showAlert(
	// 		"本平台将收取您的5%作为手续费"
	// 	)
	// }

}
